<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class AndroidFunc extends CI_Controller {

	function __construct() {

		parent::__construct();
	}

	public function index()
	{	
		echo 'Welcome to Call Secret Application';
	}

	//Storing new user and returns user details
   
   	function storeUser($gcmRegId, $user_id, $consumerEmail, $gcmType) {
	   
        // insert user into database
        $result = mysql_query("INSERT INTO gcm_users(gcm_regid, user_id, email, created_at, gcm_type) VALUES('$gcmRegId', '$user_id', '$consumerEmail', NOW(), '$gcmType')");
		
        // check for successful store
        if ($result) {
			
            // get user details
            $id = mysql_insert_id(); // last inserted id
            $result = mysql_query("SELECT * FROM gcm_users WHERE id = $id") or die(mysql_error());
            // return user details
            if (mysql_num_rows($result) > 0) {
                return mysql_fetch_array($result);
            } else {
                return false;
            }
			
        } else {
            return false;
        }
    }
	
	//Storing push queue
   	function storePushQueue($gcmRegId, $message, $api_code) {
	   
        // insert user into database
        $result = mysql_query("INSERT INTO push_queue(gcm_regid, message, time_queued, api_code) VALUES('$gcmRegId', '$message', NOW(), '$api_code')");
		
        // check for successful store
        if ($result) {
			
            // get user details
            $id = mysql_insert_id(); // last inserted id
            $result = mysql_query("SELECT * FROM push_queue WHERE message_id = $id") or die(mysql_error());
            // return user details
            if (mysql_num_rows($result) > 0) {
                return mysql_fetch_array($result);
            } else {
                return false;
            }
			
        } else {
            return false;
        }
    }

    // Getting all registered users
  	function getAllUsers() {
		$result = array();
		$rs = mysql_query("select * FROM gcm_users WHERE active = true");
		while($row = mysql_fetch_array($rs)){
			$result[count($result)] = $row;
		}
        return $result;
    }
	
	// 
  	function findDevicesUser($user_id) {
        $result = array();
		$rs = mysql_query("select * FROM gcm_users WHERE user_id = '$user_id' AND active = TRUE");
		while($row = mysql_fetch_array($rs)){
			$result[count($result)] = $row;
		}
        return $result;
    }

    // Validate user
  	function isUserExisted($email) {
        $result    = mysql_query("SELECT email from gcm_users WHERE email = '$email' AND active = TRUE");
        $NumOfRows = mysql_num_rows($result);
        if ($NumOfRows > 0) {
            // user existed
            return true;
        } else {
            // user not existed
            return false;
        }
    }
	
	// Validate device
  	function isRegIdExisted($regId) {
        $result    = mysql_query("SELECT gcm_regid from gcm_users WHERE gcm_regid = '$regId' and active = TRUE");
        $NumOfRows = mysql_num_rows($result);
        if ($NumOfRows > 0) {
            // user existed
            return true;
        } else {
            // user not existed
            return false;
        }
    }
	
	// unregister device
  	function unRegisterDevice($regId) {
          $result = mysql_query("UPDATE gcm_users SET active = FALSE WHERE gcm_regid = '$regId'");
		
        // check for successful store
        if ($result) {
			return true;
        } else {
            return false;
        }
    }
	
	// unregister device
    function updatedPushQueueApi($regId, $apiCode) {
          $result = mysql_query("UPDATE push_queue SET updated = 1 WHERE gcm_regid = '$regId' AND api_code = '$apiCode'");
		
        // check for successful store
        if ($result) {
			return true;
        } else {
            return false;
        }
    }
	
	function findQueueNotSync($regId) {
        $result = array();
		$rs = mysql_query("select * FROM push_queue WHERE gcm_regid = '$regId' AND updated = 0");
		while($row = mysql_fetch_array($rs)){
			$result[count($result)] = $row;
		}
        return $result;
    }
	
	//Sending Push Notification
   	function send_push_notification_android($registatoin_ids, $msg, $apiCode) {
        $message = array("message" => $msg, "apiCode" => $apiCode);
		$regArray[]=$registatoin_ids;
		$url = 'https://android.googleapis.com/gcm/send';

		$fields = array('registration_ids' => $regArray, 'data' => $message);
		$headers = array( 'Authorization: key=' . GOOGLE_API_KEY,'Content-Type: application/json');

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

		$result=curl_exec($ch);
		echo $result; 
		if($result==FALSE)
		{
			die('Curl Failed');
		}
		curl_close($ch);
    }
	
	//Sending Push Notification
    function send_push_notification_ios($registatoin_ids, $msg, $apiCode) {
		$obj = APNS_Push::global_instance();
		$obj->start();
		$obj->sendNotification("1", $registatoin_ids, "{\"aps\":{\"alert\":\"" . $msg .  "\"" . ",\"sound\":\"default\"" . ",\"apiCode\":\"" . $apiCode . "\"" . ",\"message\":\"" . $msg . "\"" . "}}");
       //$obj->sendNotification("1", "23691b3ff44aeb0290a08c59ace87ac1d9fcf8d876feaa23b0e5ef203ac59ba2", "{\"aps\":{\"alert\":\"ccccccc ccccc\",\"sound\":\"default\"}}");
	   //$obj->disconnectFromAPNS();
    }
	
	function writeToLog($message)
	{
		if ($fp = fopen(LOG_FILE, 'at'))
		{
			fwrite($fp, date('c') . ' ' . $message . PHP_EOL);
			fclose($fp);
		}
	}

}